const app = getApp()
const api = app.globalData.api
Page({
    data: {
        item: [],
        from: '',
        isTax: '0',
    },
    confirm: async function () {
        let obj = e.currentTarget.dataset
        if (obj.materialid) {
            wx.navigateTo({
                url: 'materialDetail?id=' + obj.materialid
            })
        }
    },
    formSubmit: async function (e) {
        let data = e.detail.value,
            saleData = wx.getStorageSync('saleData') ? wx.getStorageSync('saleData') : {}
        if (data) {
            // 初始化部分值
            data['rate'] = Number(data['rate'])
            data['price'] = Number(data['price'])
            if(this.data.isTax == '0'){
              data['taxMoney'] = (data['num']*data['price']*data['rate']).toFixed(app.globalData.setData.amount)
              data['total'] = (data['num']*data['price']*(1+data['rate'])).toFixed(app.globalData.setData.amount)
            }else{
              data['total'] = (data['num']*data['price']).toFixed(app.globalData.setData.amount)
              data['taxMoney'] = (data['total']/(1+data['rate'])*data['rate']).toFixed(app.globalData.setData.amount)
            }
            data['moneyWithOutTax'] = (data['total'] - data['taxMoney']).toFixed(app.globalData.setData.amount)
            data['id'] = data.id ? data.id : api.suiji()
            saleData[data.materialId] = data
            api.showToast('选择成功')
            wx.setStorageSync('saleData', saleData)
            wx.navigateBack({
                delta: (this.data.from === 'add') ? 1 : 2
            })
        }
    },
    // 时间关系，这个bug 不知道是啥
    onStepperChange(obj) {
        this.setData({['item.num']: obj.detail})
    },
    rateConfirm(obj) {
        const val = parseFloat(obj.detail)
        if (val >= 1) {
            api.showToast('税率不能超过 100%', 'none')
            this.setData({
                ['item.rate']: 0,
            })
        }
    },
    onLoad: async function (obj) {
        const id = obj.materialId ? obj.materialId : '',
            from = obj.from ? obj.from : '',
            string = obj.data ? obj.data : '',
            isTax = obj.isTax ? obj.isTax : '0'
        let array = []
        try {
            if (id.length > 0) {
                const saleData = wx.getStorageSync('saleData')
                array = saleData[id]
            } else {
                array = api.jsonToArray(api.urlDecode(string))
                array['num'] = 1
            }
            this.setData({
                item: array,
                from: from,
                isTax: isTax
            })
        } catch (e) {
            wx.navigateBack({delta: 1})
            api.showToast('参数错误')
        }
    }
});